package com.team24.hotel.service.impl;

import com.team24.hotel.domain.Role;
import com.team24.hotel.domain.User;
import com.team24.hotel.mapper.RoleMapper;
import com.team24.hotel.mapper.UserMapper;
import com.team24.hotel.service.RoleService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class

RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Role> findAll() {
        return roleMapper.selectAll();
    }

    @Override
    public Role findByPrimaryKey(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int saveOrUpdate(Role role, String permissionIds) {
        if (role.getRoleId() != null) {
            int upd = roleMapper.updateByPrimaryKey(role);
            updateRoleAndPermission(role.getRoleId(), permissionIds);
            return upd;
        } else {
            int ist = roleMapper.insert(role);
            int insertedRoleId = roleMapper.selectLastInsertId();
            saveRoleAndPermission(insertedRoleId, permissionIds);
            return ist;
        }
    }

    @Override
    public int saveRoleAndPermission(Integer roleId, String permissionIds) {
        if (!StringUtils.isNotBlank(permissionIds)) return 0;
        int count = 0;
        String[] pids = permissionIds.split(",");
        for (String pid : pids
        ) {
            count++;
            roleMapper.insertRoleAndPermission(roleId, Integer.parseInt(pid));
        }
        return count;
    }

    @Override
    public int updateRoleAndPermission(Integer roleId, String permissionIds) {
        int count = 0;
        roleMapper.deleteRoleAndPermission(roleId);
        count = saveRoleAndPermission(roleId, permissionIds);
        return count;
    }

    @Override
    public int deleteRole(Integer roleId) {
        List<User> users = userMapper.selectByRoleId(roleId);
        for (User user : users
        ) {
            user.setRoleId(null);
            userMapper.updateByPrimaryKey(user);
        }
        roleMapper.deleteRoleAndPermission(roleId);
        return roleMapper.deleteByPrimaryKey(roleId);
    }
}
